import React, { ReactElement } from 'react';
import { Keyboard } from 'react-native';

import { modalOpen, modalClose, toolTipOpen } from '../../util/global';
import navigator from '../../util/navigator';
import PortraitAlert from '../../components/Alert/PortraitAlert';
import { UserApi } from '../../api';

// 返回
export const back = (): void => {
  navigator.goBack();
};

export const save = (password: string): void => {
  UserApi.setPassword({ passwd: password }).then((res): void => {
    if (res.code === 0) {
      toolTipOpen({ desc: '修改密码成功' });
      back();
    }
  });
};

export const sureSave = (password: string, verifyPassword: string): void => {
  Keyboard.dismiss();

  if (password !== verifyPassword) {
    toolTipOpen({ desc: '两次输入密码不一致' });
    return;
  }

  if (password.length < 6) {
    toolTipOpen({ desc: '密码长度不足' });
    return;
  }

  if (
    password.includes('<') ||
    password.includes('>') ||
    password.includes('/') ||
    password.includes('script') ||
    password.includes(' ') ||
    !password.match(/^([A-Za-z0-9$@$!%*?&]*)$/)
  ) {
    toolTipOpen({ desc: '密码不能含有特殊字符' });
    return;
  }

  let count = 0;

  if (password.match(/.*[0-9]{1,}.*/)) {
    count += 1;
  }

  if (password.match(/.*[a-z]{1,}.*/)) {
    count += 1;
  }

  if (password.match(/.*[A-Z]{1,}.*/)) {
    count += 1;
  }

  if (password.match(/.*[$@$!%*?&]{1,}.*/)) {
    count += 1;
  }

  if (count >= 2) {
    modalOpen({
      Type: (): React.ReactElement => (
        <PortraitAlert
          title="确认修改密码？"
          sureDesc="确认"
          cancelDesc="取消"
          cancelAction={modalClose}
          sureAction={(): void => {
            modalClose();
            save(password);
          }}
        />
      ),
      needBack: true
    });
  } else {
    toolTipOpen({ desc: '密码不符合规则' });
  }
};
